/* Copyright 2017, 2018, 2019, 2020 Gabriel Czernikier
 *
 * This file is part of Côtehaus.
 * Côtehaus is free software: you can redistribute it and/or modify
 * it under the terms of one of the following:
 * 1. The same dual license as that of Côtehaus itself, of which individual licenses are
 * the MIT License and the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 2. The MIT License.
 * 3. The GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * Côtehaus is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * MIT License and the GNU General Public License for more details.
 * You should have received a copy of the MIT License and the GNU General Public License
 * along with Côtehaus.  If not, see <https://opensource.org/licenses/MIT> and <http://www.gnu.org/licenses/>.
 */
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include "composer.h"
#include "types.h"

uint16_t map_item_type_ary[] = {0/*unused*/, 0x0000, 0x0001, 0x0002, 0x0003, 0x1001, 0x1000, 0x2002};   // positionally parented/matched with the order of either up_bounds_ary or alignment_ary (actually the same order)

LIST_HEAD(map_list_head);

void
build_map_list() {
	majors_size_ary[NH_MAP_LIST_IDX] = 1;
	struct size_data *sd;
	// map_list's size
	sd = for_uint32_t(&sd);
	int maplist_length = sizeof(uint32_t);
	*(int *)sd->data = NH_UP_BOUNDS_SZ-1;
	list_add_tail(&sd->size_data_list, &map_list_head);
	for(int i=1; i<NH_UP_BOUNDS_SZ; i++) {
		// map_item's type
		for_uint16_t(&sd);
		*(int *)sd->data = map_item_type_ary[i];
		list_add_tail(&sd->size_data_list, &map_list_head);
		// map_item's unused
		for_uint16_t(&sd);
		*(int *)sd->data = 0;
		list_add_tail(&sd->size_data_list, &map_list_head);
		// map_item's size
		for_uint32_t(&sd);
		*(int *)sd->data = majors_size_ary[i];
		list_add_tail(&sd->size_data_list, &map_list_head);
		// map_item's offset
		for_uint32_t(&sd);
		*(int *)sd->data = up_bounds_ary[i-1];
		list_add_tail(&sd->size_data_list, &map_list_head);
		maplist_length += 12;  // 2 * sizeof(uint16_t) + 2 * sizeof(uint32_t)
	}
	bounds_move(NH_MAP_LIST_IDX, maplist_length);
	buf_len[NH_MAP_LIST_IDX] = maplist_length;
}

void pack_map_list() {
	struct list_head *tmp;
	list_for_each(tmp, &map_list_head){
		struct size_data *sd = list_entry(tmp, struct size_data, size_data_list);
		BUFFER_WRITE(buffer[NH_MAP_LIST_IDX], buf_len[NH_MAP_LIST_IDX], sd->data, buf_offset[NH_MAP_LIST_IDX], sd->size)
	}

}
